package com.ch.web.redis;

import com.ch.web.requestDto.xyUser.RegisterCodeDtoForm;
import com.ch.web.vo.EmailCacheVo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class EmailCache {
    private static final Map<String, EmailCacheVo> EMAIL_CACHE_VO_MAP = new ConcurrentHashMap<>(256);

    public void addEmailCode(String email, EmailCacheVo vo) {
        EMAIL_CACHE_VO_MAP.putIfAbsent(email, vo);
    }

    public EmailCacheVo getByToken(String email) {
        return EMAIL_CACHE_VO_MAP.get(email);
    }

    /**
     * 模仿redis  redis也是大多数访问的时候进行判断是否过期
     * @param email
     * @return
     */
    public Boolean isNotExpire(String email) {
        EmailCacheVo emailCacheVo = EMAIL_CACHE_VO_MAP.get(email);
        if (ObjectUtils.isEmpty(emailCacheVo)) {
            return false;
        }
        long expire = emailCacheVo.getExpire().getTime();
        long nowTime = new Date().getTime();
//        说明没有过期
        return nowTime - expire < 0;
    }

    public Boolean isHaveCode(String email) {
        EmailCacheVo emailCacheVo = EMAIL_CACHE_VO_MAP.get(email);
        return emailCacheVo == null;
    }

    public Boolean matchCode(RegisterCodeDtoForm dtoForm) {
        EmailCacheVo emailCacheVo = EMAIL_CACHE_VO_MAP.get(dtoForm.getEmail());
        return emailCacheVo.getCode().intValue() == (Integer.parseInt(dtoForm.getCode()));
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void clearExpireCode() {
            if (EMAIL_CACHE_VO_MAP.size() > 0) {
                for (Map.Entry<String, EmailCacheVo> stringEmailCacheVoEntry : EMAIL_CACHE_VO_MAP.entrySet()) {
                    String key = stringEmailCacheVoEntry.getKey();
                    long time = new Date().getTime();
                    long time1 = stringEmailCacheVoEntry.getValue().getExpire().getTime();
                    if ( time - time1 >0){
                        System.out.println(time-time1);
                        EMAIL_CACHE_VO_MAP.remove(key);
                    }
                }
            }
    }
}
